package com.hspedu.inputStream;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * @author LiuJinTao
 * @className FileInputStream_
 * @date 2024/06/26 23:10
 * @description 字节输入流
 */
public class FileInputStream_ {
    public static void main(String[] args) {

    }

    @Test
    public void readFile01() {
        String filePath = "e:\\hello.txt";
        int readDate = 0;
        FileInputStream fileInputStream = null;
        try {
            // 创建 FileInputStream 对象，用于读取文件
            fileInputStream = new FileInputStream(filePath);
            // 从该输入流读取一个字节的数据，如果没有输入可用，此方法将阻止
            // 如果返回-1，表示读取完毕
            while ((readDate = fileInputStream.read()) != -1) {
                System.out.print((char) readDate);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

    // 使用 read(byte[] b) 读取文件
    @Test
    public void readFile02() {
        String filePath = "e:\\hello.txt";
        int readDate = 0;
        // 字节数组
        byte[] bytes = new byte[8];// 一次读8个字节
        int readLength = 0;
        FileInputStream fileInputStream = null;
        try {
            // 创建 FileInputStream 对象，用于读取文件
            fileInputStream = new FileInputStream(filePath);
            // 从该输入流读取最多b.length字节的数据到字节数组，此方法将阻塞直到某些输入可用
            // 如果返回-1，表示读取完毕
            // 如果读取正常，返回实际读取的字节数
            while ((readLength = fileInputStream.read(bytes)) != -1) {
                System.out.print(new String(bytes, 0, readLength));// 转成字符显示
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}
